package com.ymt.bpm.web.rest.platform.fauth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.model.POrg;
import com.ymt.bpm.service.platform.fauth.FaOrgService;
import com.ymt.bpm.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import java.util.List;
import java.util.Map;

/**
 * Created by Johnny on 2017/2/15.
 */
@RestController
@RequestMapping("/api/v1/fa")
public class FaOrgResource {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FaOrgService rs;

    @RequestMapping(value="/orgs/allByTenant", method = RequestMethod.GET)
    public JSONArray allByTenant(HttpServletRequest req, @QueryParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        if (log.isDebugEnabled()) {
            log.debug("allByTenant tenantId=" + tenantId);
            log.debug("allByTenant timezoneOffset=" + timezoneOffset);
        }
        return rs.selectAllByTenant(tenantId, timezoneOffset);
    }

    /**
     * check if a orgName exists in the same level
     * @param req
     * @return
     */
    @RequestMapping(value="/orgs/checkName",
            produces = "plain/text")
    public String checkName(HttpServletRequest req) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String orgName = req.getParameter("orgName");
        String parentId = req.getParameter("parentId");
        String orgId = req.getParameter("orgId");
        if (log.isDebugEnabled()) {
            log.debug("checkName tenantId=" + tenantId);
            log.debug("checkName orgName=" + orgName);
            log.debug("checkName parentId=" + parentId);
            log.debug("checkName orgId=" + orgId);
        }
        return rs.checkName(tenantId, parentId, orgId, orgName);
    }

    /**
     * save org
     * @param req
     * @param org
     * @return
     */
    @RequestMapping(value="/org/save",
            method= RequestMethod.POST)
    public JSONObject save(HttpServletRequest req, POrg org, @QueryParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("save tenantId=" + tenantId);
            log.debug("save loginName=" + loginName);
            log.debug("save displayName=" + displayName);
            log.debug("save orgId=" + org.getOrgId());
            log.debug("save orgName=" + org.getOrgName());
        }
        return rs.save(tenantId, loginName, displayName, org, timezoneOffset);
    }

    /**
     * get an org
     * @param req
     * @param orgId
     * @return
     */
    @RequestMapping(value="/org/{orgId}",
            method= RequestMethod.GET)
    public POrg get(HttpServletRequest req, @PathVariable("orgId")String orgId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        if (log.isDebugEnabled()) {
            log.debug("save tenantId=" + tenantId);
            log.debug("save orgId=" + orgId);
        }
        return rs.get(tenantId, orgId);
    }

    /**
     * delete an org
     * @param req
     * @param orgId
     * @return
     */
    @RequestMapping(value="/org/{orgId}",
            method= RequestMethod.DELETE)
    public JSONObject del(HttpServletRequest req, @PathVariable("orgId")String orgId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("del tenantId=" + tenantId);
            log.debug("del orgId=" + orgId);
        }
        return rs.del(tenantId, loginName, displayName, orgId);
    }

    @RequestMapping(value="/orgs/allByTenantWithPos", method = RequestMethod.GET)
    public JSONArray allByTenantWithPos(HttpServletRequest req, @QueryParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        if (log.isDebugEnabled()) {
            log.debug("allByTenantWithPos tenantId=" + tenantId);
            log.debug("allByTenantWithPos timezoneOffset=" + timezoneOffset);
        }
        return rs.selectAllByTenantWithPos(tenantId, timezoneOffset);
    }

    /**
     * get users in org
     * @param req
     * @param orgId
     * @return
     */
    @RequestMapping(value="/org/{orgId}/users",
            method= RequestMethod.GET)
    public JSONObject usersInOrg(HttpServletRequest req,
                                                @PathVariable("orgId")String orgId,
                                                @RequestParam(name="sort", required=false)String sort,
                                                @RequestParam(name="order", required=false)String order) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String offset = req.getParameter("offset");
        String limit = req.getParameter("limit");
        if (log.isDebugEnabled()) {
            log.debug("usersInOrg tenantId=" + tenantId);
            log.debug("usersInOrg orgId=" + orgId);
            log.debug("usersInOrg sort=" + sort);
            log.debug("usersInOrg order=" + order);
            log.debug("usersInOrg offset=" + offset);
            log.debug("usersInOrg limit=" + limit);
        }
        return rs.usersInOrg(tenantId, orgId, Integer.parseInt(offset), Integer.parseInt(limit), sort, order);
    }

    /**
     * get users in org
     * @param req
     * @param orgId
     * @return
     */
    @RequestMapping(value="/org/{orgId}/usersDhx",
            method= RequestMethod.POST)
    public String usersInOrgDhx(HttpServletRequest req,
                                 @PathVariable("orgId")String orgId,
                                    @RequestParam("queryParams")String queryParams,
                                    @RequestParam("fromRow")int fromRow,
                                    @RequestParam("toRow")int toRow,
                                    @RequestParam("timezoneOffset")int timezoneOffset,
                                    @RequestParam(value="ordercolumns")String ordercolumns) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        if (log.isDebugEnabled()) {
            log.debug("usersInOrgDhx tenantId=" + tenantId);
            log.debug("usersInOrgDhx lang=" + lang);
            log.debug("usersInOrgDhx orgId=" + orgId);
            log.debug("usersInOrgDhx queryParams=" + queryParams);
            log.debug("usersInOrgDhx fromRow=" + fromRow);
            log.debug("usersInOrgDhx toRow=" + toRow);
            log.debug("usersInOrgDhx timezoneOffset=" + timezoneOffset);
            log.debug("usersInOrgDhx ordercolumns=" + ordercolumns);
        }
        return rs.usersInOrgDhx(tenantId, orgId, queryParams, fromRow, toRow, timezoneOffset, lang, ordercolumns);
    }

    /**
     * get users in org-position
     * @param req
     * @param orgId
     * @param posId
     * @return
     */
    @RequestMapping(value="/org/{orgId}/{posId}/users",
            method= RequestMethod.GET)
    public JSONObject usersInOrgPos(HttpServletRequest req,
                                                   @PathVariable("orgId")String orgId,
                                                   @PathVariable("posId")String posId,
                                                   @RequestParam(name="sort", required=false)String sort,
                                                   @RequestParam(name="order", required=false)String order) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String offset = req.getParameter("offset");
        String limit = req.getParameter("limit");
        if (log.isDebugEnabled()) {
            log.debug("usersInOrgPos tenantId=" + tenantId);
            log.debug("usersInOrgPos orgId=" + orgId);
            log.debug("usersInOrgPos posId=" + posId);
            log.debug("usersInOrgPos sort=" + sort);
            log.debug("usersInOrgPos order=" + order);
            log.debug("usersInOrgPos offset=" + offset);
            log.debug("usersInOrgPos limit=" + limit);
        }
        return rs.usersInOrgPos(tenantId, orgId, posId, Integer.parseInt(offset), Integer.parseInt(limit), sort, order);
    }

    @RequestMapping(value="org/{orgId}/addOrgPos",
        method = RequestMethod.POST)
    public JSONObject addOrgPos(HttpServletRequest req,
                                @PathVariable("orgId")String orgId,
                                @RequestParam("posId")String posId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("addOrgPos tenantId=" + tenantId);
            log.debug("addOrgPos orgId=" + orgId);
            log.debug("addOrgPos posId=" + posId);
        }
        JSONObject rtn = new JSONObject();
        int ret = rs.addPosition(tenantId, loginName, displayName, orgId, posId);
        rtn.put("result", ret);
        return rtn;
    }

    @RequestMapping(value="org/{orgId}/delOrgPos",
            method = RequestMethod.DELETE)
    public JSONObject delOrgPos(HttpServletRequest req,
                                @PathVariable("orgId")String orgId,
                                @RequestParam("posId")String posId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("delOrgPos tenantId=" + tenantId);
            log.debug("delOrgPos orgId=" + orgId);
            log.debug("delOrgPos posId=" + posId);
        }
        JSONObject rtn = new JSONObject();
        int ret = rs.deletePosition(tenantId, loginName, displayName, orgId, posId);
        rtn.put("result", ret);
        return rtn;
    }

    @RequestMapping(value="org/{orgId}/addOrgPosUser",
            method = RequestMethod.POST)
    public JSONObject addOrgPosUser(HttpServletRequest req,
                                    @PathVariable("orgId")String orgId,
                                    @RequestParam(name="posId",required=false)String posId,
                                    @RequestParam("userId")String userId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("addOrgPosUser tenantId=" + tenantId);
            log.debug("addOrgPosUser orgId=" + orgId);
            log.debug("addOrgPosUser posId=" + posId);
            log.debug("addOrgPosUser userId=" + userId);
        }
        JSONObject rtn = rs.addPositionUser(tenantId, loginName, displayName, orgId, posId, userId);
        return rtn;
    }

    @RequestMapping(value="org/{orgId}/delOrgPosUser",
            method = RequestMethod.DELETE)
    public JSONObject delOrgPosUser(HttpServletRequest req,
                                    @PathVariable("orgId")String orgId,
                                    @RequestParam(name="posId", required = false)String posId,
                                    @RequestParam("userId")String userId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("delOrgPosUser tenantId=" + tenantId);
            log.debug("delOrgPosUser orgId=" + orgId);
            log.debug("delOrgPosUser posId=" + posId);
            log.debug("delOrgPosUser userId=" + userId);
        }
        JSONObject rtn = new JSONObject();
        int ret = 0;
        if (posId!=null && posId.length()>0) {
            ret = rs.deletePositionUser(tenantId, loginName, displayName, orgId, posId, userId);
        } else {
            ret = rs.deleteOrgUser(tenantId, loginName, displayName, orgId, userId);
        }
        rtn.put("result", ret);
        return rtn;
    }

}
